<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import qs from "qs";

const codeList = ref([])
const totalCode = ref(codeList.value.length);
// 当前页码，默认为第一页
const currentPage = ref(1);
// 每页显示的条数，默认10
const pageSize = ref(10);
const copyCode = (code) => {
  navigator.clipboard.writeText(code)
      .then(() => {
        ElMessage.success("复制成功!!")
      })
      .catch(() => {
        ElMessage.error("复制失败!!")
      })
}
const getCodeList = async () => {
  try {
    const res = await axios.get("/api/code/list",{
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res.data.code === 200) {
      codeList.value = res.data.data
    }
  }catch (e){
    ElMessage.error(`服务器错误!请与管理员联系！错误: ${e.message}`)
  }
}
const addCode = async () => {
  let charStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let randomCode = '';
  for (let i = 0; i < 18; i++) {
    let randomIndex = Math.floor(Math.random() * charStr.length);
    randomCode += charStr.charAt(randomIndex);
  }
  try {
    const res = await axios.post("/api/code/add", qs.stringify({
      cCode: randomCode
    }))
    if (res.data.code === 200) {
      ElMessage.success("新增成功!");
      await getCodeList()
    } else {
      ElMessage.error("新增失败!!")
    }
  }catch (e){
    ElMessage.error(`服务器错误!请与管理员联系！错误: ${e.message}`)
  }
}
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getCodeList()
};
onMounted(()=>{
  getCodeList()
})
</script>

<template>
<div class="code_container">
  <el-row :gutter="20">
    <el-col :span="6">
      <el-row>
        <el-col :span="6">
          <el-button icon="Plus" plain type="primary" @click="addCode">新增授权码</el-button>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
  <el-table :data="codeList">
    <el-table-column align="center" prop="CId" label="授权码ID"></el-table-column>
    <el-table-column align="center" prop="CCode" label="授权码"></el-table-column>
    <el-table-column align="center" prop="CStatus" label="授权码状态">
      <template #default="scope">
        <el-tag v-if="scope.row.CStatus === 1" type="danger">已使用</el-tag>
        <el-tag v-else type="success">未使用</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="100">
      <template #default="scope">
        <el-button type="text" @click="copyCode(scope.row.CCode)" :disabled="scope.row.CStatus === 1">复制</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCode"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
  />
</div>
</template>

<style scoped>
.el-col {
  margin-bottom: 5px;
}

.el-table th, .el-table td {
  text-align: center !important;
}
</style>